package com.mdx.zhizhao.service;

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mdx.zhizhao.controller.COSandAI;
import com.mdx.zhizhao.domain.Evaluate;
import com.mdx.zhizhao.domain.Job;
import com.mdx.zhizhao.domain.Seeker;
import com.mdx.zhizhao.persistence.EvaluateMapper;
import com.mdx.zhizhao.persistence.JobMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class MatchService {

    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private SeekerService seekerService;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private COSandAI cosandAI;
    public void match(String seekerid) throws IOException, NoApiKeyException, InputRequiredException {
        Seeker seeker = seekerService.selectSeeker(seekerid);
        String s=COSandAI.select(seekerid);
        JSONObject jsonObject1 = JSON.parseObject(s);
        JSONObject resume = jsonObject1.getJSONObject("resume");
        String part1 = resume.getString("part1");
        String part2 = resume.getString("part2");
        String part3 = resume.getString("part3");
        String part4 = resume.getString("part4");
        String part5 = part1+part2+part3+part4;
        JSONObject context = jsonObject1.getJSONObject("context");
        String expectlocation=context.getString("expectlocation");
        String expectsalary=context.getString("expectsalary");
        seeker.setExpectlocation(expectlocation);
        seeker.setExpectsalary(expectsalary);
        seeker.setSeekerdetail(part5);
        List<Job> jobList = jobMapper.selectList(null);
        for(int i = 0; i < jobList.size(); i++){
            ObjectMapper objectMapper = new ObjectMapper();
            String json1 = objectMapper.writeValueAsString(jobList.get(i));
            String json2 = objectMapper.writeValueAsString(seeker);
            String json3 =appCall(json1+json2);
            try {
                Evaluate evaluate = objectMapper.readValue(json3, Evaluate.class);
            System.out.println(evaluate);
            // 先检查是否存在符合条件的数据
            QueryWrapper<Evaluate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("seekerid", evaluate.getSeekerid()).eq("jobid", evaluate.getJobid());
            Evaluate existingEvaluate = evaluateMapper.selectOne(queryWrapper);
            if (existingEvaluate!= null) {
                // 如果存在，先删除
                evaluateMapper.delete(queryWrapper);
            }
            // 然后插入新数据
            evaluateMapper.insert(evaluate);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String appCall(String context)
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey("sk-a366c2b70744440b96b9a81c569a7d93")
                .appId("44b7b3efa5124e509a786aea8dbc3807")
                .prompt(context)
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
//
//        System.out.printf("text: %s\n",
//                result.getOutput().getText());
        return result.getOutput().getText();
    }

//    public static void test(String[] args) {

//        try {
//            appCall();
//        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
//            System.err.println("message："+e.getMessage());
//            System.out.println("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
//        }
//        System.exit(0);
//    }
}